06. Solution: Writing Unit Tests
Solution: Writing Unit Tests
ND079 JPND C3 L4 A05 Writing Unit Tests With JUnit Exercise Solution
Writing a Unit Test
You should have created a class called TotalsCalculatorTest
in the com.udacity.cart.service
package of the src/test/java
directory. Aside from the awkward design of the class under test, this test is fairly simple. We create a new TotalsCalculator
, populate a list of CartItems
, and then use the calculator to return a CartTotals
. Then we use assertAll
to execute two different assertEquals
methods on the subtotal and taxes. Note that the assertEquals(double)
method takes an additional parameter specifying the acceptable variance, because doubles are floating point numbers that will rarely be 100% equal.
public class TotalsCalculatorTest {
@Test
public void getTotals_givenMultipleItems_sumsPriceAndTax() {
// Arrange
TotalsCalculator totalsCalculator = new TotalsCalculator();
List<CartItem> itemList = List.of(
new CartItem("Soda", 3.00, 0.50),
new CartItem("Small peperoni pizza", 6.00, 0.60),
new CartItem("Fries", 2.00, 0.10)
);
// Act
CartTotals totals = totalsCalculator.getTotals(itemList);
// Assert
assertAll("Totals match",
() -> assertEquals(11.0, totals.getSubtotal(), 0.001),
() -> assertEquals(1.2, totals.getTaxes(), 0.001)
);
}
}